/*
 * @Autor: dingxiaolin
 * @Date: 2020-04-14 13:30:31
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-09-01 22:31:59
 */
const getRawBody = require('raw-body');
const request = require('request-promise')
const random =require('string-random');


// 查询快递号?
const search = async(postid) => {
    var options = {
        uri: 'https://www.kuaidi100.com/autonumber/autoComNum',
        qs: {
            resultv2:1,
            text: postid,
        },
        //resolveWithFullResponse: true,
        json: true // Automatically parses the JSON string in the response
    };

    const type = await request(options) // "comCode": "yuantong",
    console.log('type',type)

    var options2 = {
        uri: 'https://www.kuaidi100.com/query',
        qs: {
            type: type.auto[0].comCode,
            postid:postid,
            temp:'0.'+random(16,{letters:false}),  
            phone:''
        },
        headers: {
            'Referer': 'https://www.kuaidi100.com/?from=openv',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36'
        },
        json: false //这里必须是false 要不然查不出正确的结果
    };
    const detail = await request(options2)
    return detail
}

// 入口函数
module.exports.handler = function (req, resp, context) {
    getRawBody(req, async (err, body) => {
        if (req.queries.id) {
            let data = JSON.parse(await search(req.queries.id))
            console.log('data',data)
            if (data.message=='ok') {
                await sendResp(data, true)
            }
            else {
                await sendResp(data.message, false)
            }
        } else {
            await sendResp("请输入查询快递号", false)
        }
    });

    // 返回
    sendResp = (data, boolean) => {
        resp.setHeader('content-type', 'application/json');
        try {
            resp.send(JSON.stringify({
                success: boolean,
                data: data
            }));
        }
        catch (err) {
            resp.send(JSON.stringify({
                success: false,
                data: err.message
            }));
        }
    }

}